<template>
  <div class="form-container">
    <el-card class="form-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <el-icon><EditPen /></el-icon>
          <span>编辑申请 - {{ application.description }}</span>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        label-position="left"
      >
        <!-- 申请人信息 -->
        <el-form-item label="申请人姓名" prop="applicantName">
          <el-input
            v-model="formData.applicantName"
            placeholder="请输入申请人姓名"
            clearable
            :prefix-icon="User"
          />
        </el-form-item>

        <!-- 报销金额 -->
        <el-form-item label="报销金额" prop="amount">
          <el-input-number
            v-model="formData.amount"
            :min="0"
            :precision="2"
            :step="0.01"
            placeholder="请输入报销金额"
            style="width: 100%"
            :prefix-icon="Money"
          />
        </el-form-item>

        <!-- 费用类型 -->
        <el-form-item label="费用类型" prop="expenseType">
          <el-select
            v-model="formData.expenseType"
            placeholder="请选择费用类型"
            style="width: 100%"
            clearable
          >
            <el-option
              v-for="item in expenseTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- 报销事由 -->
        <el-form-item label="报销事由" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="4"
            placeholder="请详细描述报销事由，包括费用用途、时间、地点等"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <!-- 发票信息 -->
        <el-form-item label="发票信息" prop="invoiceInfo">
          <el-input
            v-model="formData.invoiceInfo"
            type="textarea"
            :rows="3"
            placeholder="请填写发票号码、开票日期等信息（可选）"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <!-- 驳回原因提示 -->
        <el-form-item>
          <el-alert
            title="驳回原因"
            :description="getLastRejectReason()"
            type="warning"
            :closable="false"
            show-icon
          />
        </el-form-item>

        <!-- 表单操作按钮 -->
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="handleSubmit" :icon="Check">
            {{ loading ? '提交中...' : '重新提交' }}
          </el-button>
          <el-button @click="handleReset" :icon="Refresh"> 重置修改 </el-button>
          <el-button @click="$emit('cancel')" :icon="Close"> 取消编辑 </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus' // 引入Element Plus消息组件
import { EditPen, User, Money, Check, Refresh, Close } from '@element-plus/icons-vue' // 引入图标
import { useApplicationStore } from '@/store/application'
import type { ReimbursementApplication } from '@/services/models'

const props = defineProps<{
  application: ReimbursementApplication
}>()

const emit = defineEmits<{
  cancel: []
  success: [application: ReimbursementApplication]
}>()

const store = useApplicationStore()

// 定义表单数据接口
interface FormData {
  applicantName: string
  amount: number
  description: string
  expenseType: string
  invoiceInfo: string
}

// 费用类型选项
const expenseTypeOptions = [
  { value: 'office', label: '办公用品' },
  { value: 'travel', label: '差旅费用' },
  { value: 'entertainment', label: '招待费用' },
  { value: 'equipment', label: '设备采购' },
  { value: 'training', label: '培训费用' },
  { value: 'other', label: '其他费用' },
]

// 表单验证规则
const formRules = {
  applicantName: [
    { required: true, message: '请输入申请人姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' },
  ],
  amount: [
    { required: true, message: '请输入报销金额', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '金额必须大于0', trigger: 'blur' },
  ],
  expenseType: [{ required: true, message: '请选择费用类型', trigger: 'change' }],
  description: [
    { required: true, message: '请输入报销事由', trigger: 'blur' },
    { min: 10, max: 500, message: '事由长度在 10 到 500 个字符', trigger: 'blur' },
  ],
}

// 初始化表单数据
const formData = reactive<FormData>({
  applicantName: '',
  amount: 0,
  description: '',
  expenseType: '',
  invoiceInfo: '',
})

const loading = ref(false)
const formRef = ref() // 表单引用

// 获取最后一次驳回原因
const getLastRejectReason = () => {
  const rejectRecord = props.application.history
    .filter((record) => record.action === 'reject')
    .pop()
  return rejectRecord ? rejectRecord.comment : '无驳回原因'
}

// 初始化表单数据
const initFormData = () => {
  formData.applicantName = props.application.applicantName
  formData.amount = props.application.amount
  formData.description = props.application.description
  formData.expenseType = props.application.expenseType
  formData.invoiceInfo = props.application.invoiceInfo || ''
}

// 提交表单处理函数
const handleSubmit = async () => {
  if (!formRef.value) return
  // 表单验证
  const valid = await formRef.value.validate()
  if (!valid) {
    return
  }
  try {
    // 确认重新提交
    await ElMessageBox.confirm(
      '确定要重新提交这个申请吗？修改后的内容将进入审批流程。',
      '确认重新提交',
      {
        confirmButtonText: '确定提交',
        cancelButtonText: '取消',
        type: 'info',
      },
    )

    loading.value = true

    // 调用store方法重新提交申请
    await store.updateApplicationData(props.application.id, {
      applicantName: formData.applicantName,
      amount: formData.amount,
      description: formData.description,
      expenseType: formData.expenseType,
      invoiceInfo: formData.invoiceInfo,
    })

    // 显示成功提示
    ElMessage({
      type: 'success',
      message: '申请重新提交成功！已进入部门主管审批流程。',
      duration: 3000,
    })

    // 触发成功事件
    emit('success', props.application)
  } catch (error: unknown) {
    if (error !== 'cancel') {
      // 显示错误信息
      ElMessage({
        type: 'error',
        message: `重新提交失败：${error instanceof Error ? error.message : '未知错误'}`,
        duration: 5000,
      })
    }
  } finally {
    loading.value = false
  }
}

// 重置表单到原始数据
const handleReset = async () => {
  try {
    await ElMessageBox.confirm('确定要重置所有修改吗？将恢复到原始申请内容。', '确认重置', {
      confirmButtonText: '确定重置',
      cancelButtonText: '取消',
      type: 'warning',
    })

    // 重置到原始数据
    initFormData()

    // 清除表单验证状态
    if (formRef.value && formRef.value.clearValidate) {
      formRef.value.clearValidate()
    }

    ElMessage({
      type: 'info',
      message: '已重置到原始内容',
      duration: 2000,
    })
  } catch {
    // 用户取消重置操作
  }
}

// 组件挂载时初始化表单数据
onMounted(() => {
  initFormData()
})
</script>

<style scoped>
.form-container {
  max-width: 700px;
  margin: 0 auto;
  padding: 20px;
}

.form-card {
  border-radius: 12px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.card-header .el-icon {
  font-size: 20px;
  color: #409eff;
}

/* 自定义表单样式 */
:deep(.el-form-item__label) {
  font-weight: 600;
  color: #606266;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
}

:deep(.el-textarea__inner) {
  border-radius: 8px;
}

:deep(.el-select .el-input__wrapper) {
  border-radius: 8px;
}

:deep(.el-input-number .el-input__wrapper) {
  border-radius: 8px;
}

/* 按钮样式优化 */
:deep(.el-button) {
  border-radius: 8px;
  font-weight: 500;
  padding: 12px 24px;
  margin-right: 12px;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
  border: none;
}

:deep(.el-button--primary:hover) {
  background: linear-gradient(135deg, #337ecc 0%, #2c5aa0 100%);
}

/* 提示框样式 */
:deep(.el-alert) {
  border-radius: 8px;
  border: 1px solid #e1f3d8;
}

:deep(.el-alert--warning) {
  background-color: #fdf6ec;
  border-color: #f5dab1;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .form-container {
    padding: 10px;
  }

  :deep(.el-form-item__label) {
    width: 100px !important;
  }

  :deep(.el-form-item) {
    margin-bottom: 20px;
  }
}

@media (max-width: 480px) {
  .form-container {
    padding: 5px;
  }

  :deep(.el-form-item__label) {
    width: 80px !important;
    font-size: 14px;
  }
}
</style>
